/*
 * Copyright 2007-2008 Andrew O'Malley
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package ws.quokka.plugin.jetty;

import org.mortbay.jetty.Server;

import ws.quokka.core.bootstrap_util.Logger;
import ws.quokka.core.util.InterruptableInputHandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;

import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;


/**
 * Monitor will monitor a Jetty server instance or stop a currently running instance.
 * It is based on the Jetty Monitor class and Main stop method. Unfortunately, the
 * Jetty version calls System.exit on stop which kills the JVM when stopping
 * an instance during integration testing. I assume Jetty's Maven plugin doesn't work properly
 * for this reason. Regardless, instead of trapping the System.exit, I've done
 * a clean implementation here as it removes the need for system properties, the start.jar
 * and custom security managers.
 */
public class Monitor {
    //~ Instance fields ------------------------------------------------------------------------------------------------

    private int port;
    private String key;
    private Logger logger;

    //~ Constructors ---------------------------------------------------------------------------------------------------

    public Monitor(int port, String key, Logger logger) {
        this.port = port;
        this.key = key;
        this.logger = logger;
    }

    //~ Methods --------------------------------------------------------------------------------------------------------

    /**
     * Montiors the server instance given and will interrupt the thread given
     */
    public void monitor(final Server server, final InterruptableInputHandler handler) {
        Thread thread = new Thread("JettyStopMonitor") {
                public void run() {
                    try {
                        listenForStop(handler, server);
                    } catch (Exception e) {
                        logger.error("[jetty-monitor] Unable to monitor Jetty for stop requests: " + e.getMessage());
                    }
                }
            };

        thread.setDaemon(true);
        thread.start();
    }

    private void listenForStop(InterruptableInputHandler handler, Server server)
            throws IOException {
        ServerSocket serverSocket = new ServerSocket(port, 1, getLocalHost());

        try {
            while (true) {
                Socket socket = serverSocket.accept();

                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                    if (key.equals(reader.readLine()) && "stop".equals(reader.readLine())) {
                        logger.info("[jetty-monitor] Stopping Jetty server due to stop request");

                        if (handler != null) {
                            handler.interrupt();
                        }

                        server.stop();

                        return;
                    }
                } catch (Exception e) {
                    logger.error("[jetty-monitor] Unable to process Jetty monitor socket request: " + e.getMessage());
                } finally {
                    socket.close();
                }
            }
        } finally {
            serverSocket.close();
        }
    }

    public void stop() {
        try {
            Socket socket = new Socket(getLocalHost(), port);

            try {
                OutputStream out = socket.getOutputStream();
                out.write((key + "\nstop\n").getBytes());
                out.close();
            } finally {
                socket.close();
            }
        } catch (Exception e) {
            logger.error("[jetty-monitor] Unable to send Jetty stop request: " + e.getMessage());
        }
    }

    private InetAddress getLocalHost() throws UnknownHostException {
        return InetAddress.getByName("127.0.0.1");
    }
}
